package com.ershi.controller;

import com.ershi.enums.BizCodeEnum;
import com.ershi.result.Result;
import com.ershi.service.FileService;
import com.ershi.service.MessageService;
import com.ershi.util.CommonUtil;
import com.ershi.util.SendCodeEnum;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 通用邮箱验证码相关控制器
 *
 * @author yinhuidong3@xiaomi.com
 * @since 2021/7/20
 */
@Slf4j
@RestController
@RequestMapping("/user_common")
@Api(tags = "通用功能模块")
public class CommonController {

    @Resource
    private Producer captchaProducer;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MessageService messageService;

    @Resource
    private FileService fileService;
    /**
     * 验证码过期时间 10分钟
     */
    private static final Long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10L;

    /**
     * 获取图形验证码
     */
    @ApiOperation("获取图形验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String cacheKey = getCaptchaKey(request);

        String capText = captchaProducer.createText();
        stringRedisTemplate.opsForValue().set(cacheKey, capText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = null;

        try {
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "create_date-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("验证码获取失败，错误原因：{ }", e);
        }
    }

    /**
     * 发送短信注册验证码
     */
    @ApiOperation("利用阿里云短信服务发送短信注册验证码")
    @GetMapping("send_code/{to}/{captcha}")
    public Result sendMessageCode(
            @PathVariable(value = "to", required = true) String to,
            @PathVariable(value = "captcha", required = true) String captcha,
            HttpServletRequest request
    ) {
        //获取缓存key
        String cacheKey = getCaptchaKey(request);
        String server_code = stringRedisTemplate.opsForValue().get(cacheKey);
        //如果图形验证码对比一致，则发送短信，并清除缓存中的图形验证码
        if (server_code!=null && captcha!=null && server_code.equalsIgnoreCase(captcha)){
            stringRedisTemplate.delete(cacheKey);
            return messageService.sendMessage(SendCodeEnum.USER_REGISTER,to);
        }
        return Result.buildResult(BizCodeEnum.CODE_CAPTCHA);
    }


    /**
     * 获取缓存的key
     *
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {

        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");

        String key = "user-service:captcha:" + CommonUtil.MD5(ip + userAgent);

        log.info("ip={}", ip);
        log.info("userAgent={}", userAgent);
        log.info("key={}", key);

        return key;
    }
    /**
     * 用户头像上传
     */
    @ApiOperation("用户头像上传")
    @PostMapping("upload")
    public Result uploadHeaderImg(@ApiParam(value = "文件上传",required = true)
                                  @RequestPart("file")MultipartFile file){
        String result = fileService.uploadUserHeadImg(file);
        return result !=null?Result.buildSuccess(result):Result.buildResult(BizCodeEnum.CODE_CAPTCHA);
    }
}
